package cn.com.zero.db.config;

import cn.com.zero.db.service.DynamicDataSourceService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 动态数据源
 * @createTime 2022/7/15 11:06
 */
public class DynamicDataSource extends AbstractRoutingDataSource {


    // 默认数据源key
    @Value("${spring.datasource.default-db-key}")
    private String defaultDbKey = "primary";

    // 数据源集合
    private final Map<Object, Object> dataSources = new HashMap<>();

    public DynamicDataSource() {
        super.setTargetDataSources(dataSources);
    }

    public <T extends DataSource> void addDataSource(String key, T dataSource) {
        dataSources.put(key, dataSource);
    }

    // 获取当前数据源的key值
    @Override
    protected Object determineCurrentLookupKey() {
        String currentDb = DynamicDataSourceService.currentDb();
        if (currentDb == null) {
            return defaultDbKey;
        }
        return currentDb;
    }

}
